package controllers

import (
	"fmt"

	beego "github.com/beego/beego/v2/server/web"
)

type SigninController struct {
	beego.Controller
}

type signinuser struct {
	Name string `form:"Username"`
	Pwd  string `form:"Pwd"`
}

//判断是否是管理员
var AdminNav bool

func (this *SigninController) Get() {
	// c.Data["Website"] = "beego.me"
	// c.Data["Email"] = "astaxie@gmail.com"
	flash := beego.ReadFromRequest(&this.Controller)
	err := flash.Data["error"]

	if len(err) != 0 {
		fmt.Println(err)
	}
	this.TplName = "model/login.tpl"
	this.LayoutSections = make(map[string]string)
	this.LayoutSections["IndexHead"] = "model/head.tpl"
	this.LayoutSections["IndexNavbar"] = "model/navbar.tpl"
	this.LayoutSections["IndexFoot"] = "model/foot.tpl"
	this.Layout = "index.tpl"
}

func (this *SigninController) Post() {
	// c.Data["Website"] = "beego.me"
	// c.Data["Email"] = "astaxie@gmail.com"
	// 初始化flash
	flash := beego.NewFlash()

	signinuser := signinuser{}
	err := this.ParseForm(&signinuser)
	adminpwd, _ := beego.AppConfig.String("adminpwd")
	admin, _ := beego.AppConfig.String("admin")

	if err == nil {
		if signinuser.Pwd != adminpwd {
			flash.Error("用户名或密码不一致。")
			flash.Store(&this.Controller)
			this.Redirect("/login", 302)
		}
		if signinuser.Name == admin {
			this.SetSession("name", signinuser.Name)
			AdminNav = true
			this.Redirect("/admin/table", 302)
		} else {
			flash.Error("用户名或密码不一致。")
			flash.Store(&this.Controller)
			this.Redirect("/login", 302)
		}
	}
}
